package org.flower.isme.flower.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.flower.isme.common.exception.BizException;
import org.flower.isme.common.response.BizResponseCode;
import org.flower.isme.common.response.Page;
import org.flower.isme.flower.domain.dto.*;
import org.flower.isme.flower.domain.entity.*;
import org.flower.isme.flower.domain.request.PlantsPageRequest;
import org.flower.isme.flower.domain.request.UpdatePlantRequest;
import org.flower.isme.flower.mapper.*;
import org.flower.isme.flower.service.PlantsService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Optional;


@Service
@RequiredArgsConstructor
public class PlantsServiceImpl extends ServiceImpl<PlantsMapper, Plants>
    implements PlantsService {

    private final PlantEnvironmentMapper plantEnvironmentMapper;
    private final LightDataMapper lightDataMapper;
    private final SoilDataMapper soilDataMapper;
    private final EnvironmentDataMapper environmentDataMapper;

    /**
     * 分页查询植物列表
     *
     * @param plantsPageRequest 查询信息
     * @return Page
     */
    @Override
    public Page<PlantsPageDto> queryPage(PlantsPageRequest plantsPageRequest) {
        IPage<Plants> page = plantsPageRequest.toPage();

        IPage<PlantsPageDto> convert = getBaseMapper().queryPage(page, plantsPageRequest.getPlantName()).convert(dto -> {
            PlantsPageDto dtoDto = new PlantsPageDto();
            dtoDto.setPlantName(dto.getPlantName());
            dtoDto.setId(dto.getId());
            dtoDto.setCreateTime(dto.getCreateTime());
            dtoDto.setUpdateTime(dto.getUpdateTime());
            dtoDto.setLocation(dto.getLocation());
            dtoDto.setLabelName(dto.getLabelName());
            dtoDto.setNickName(dto.getNickName());
            dtoDto.setImageUrl(dto.getImageUrl());
            return dtoDto;
        });

        return Page.convert(convert);
    }

    /**
     * 根据id删除植物
     *
     * @param id id
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void removePlant(Long id) {
        boolean exists = lambdaQuery().eq(Plants::getId, id).exists();
        if (!exists) {
            throw new BizException(BizResponseCode.NOT_FOUND, "该植物不存在");
        }
        baseMapper.deleteById(id);
    }

    /**
     * 通过id上传图片路径
     *
     * @param update 信息
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void uploadImage(UpdatePlantRequest update) {
        boolean exists = lambdaQuery().eq(Plants::getId, update.getId()).exists();
        if (!exists) {
            throw new BizException(BizResponseCode.ERR_400, "该植物不存在");
        }
        // 更新图片路径
        lambdaUpdate().eq(Plants::getId, update.getId())
                .set(Plants::getImageUrl, update.getImageUrl())
                .update();
    }

    /**
     * 通过id获取植物详情
     *
     * @param id 植物id
     * @return PlantsDetailsDto
     */
    @Override
    public PlantsDetailsDto queryPlantsDetails(Long id) {
        boolean exists = lambdaQuery().eq(Plants::getId, id).exists();
        if (!exists) {
            throw new BizException(BizResponseCode.ERR_400, "该植物不存在");
        }
        return lambdaQuery().eq(Plants::getId, id).one().convert(PlantsDetailsDto.class);
    }


    /**
     * 根据id更新植物描述
     *
     * @param update 植物详情
     */
    @Override
    public void updatePlantsDescription(UpdatePlantRequest update) {
        boolean exists = lambdaQuery().eq(Plants::getId, update.getId()).exists();
        if (!exists) {
            throw new BizException(BizResponseCode.ERR_400, "该植物不存在");
        }
        boolean updated = lambdaUpdate()
                .eq(Plants::getId, update.getId())
                .set(Plants::getDescription, update.getDescription())
                .update();

        if (!updated) {
            throw new BizException(BizResponseCode.SERVER_ERROR, "更新失败");
        }
    }

    /**
     * 通过id获取植物详情
     *
     * @param plantId 植物id
     * @return FlowerDetailsDto
     */
    @Override
    public FlowerDetailsDto queryFlowerDetailsByPlantId(Long plantId) {
        boolean exists = lambdaQuery().eq(Plants::getId, plantId).exists();
        if (!exists) {
            throw new BizException(BizResponseCode.ERR_400, "该植物不存在");
        }

        Plants plants = lambdaQuery().eq(Plants::getId, plantId).one();


        FlowerDetailsDto flowerDetailsDto = new FlowerDetailsDto();
        flowerDetailsDto.setPlantId(plants.getId());
        flowerDetailsDto.setPlantName(plants.getPlantName());
        flowerDetailsDto.setNickName(plants.getNickName());
        flowerDetailsDto.setImageUrl(plants.getImageUrl());
        flowerDetailsDto.setLabelName(plants.getLabelName());

        LambdaQueryWrapper<PlantEnvironment> queryWrapper = new LambdaQueryWrapper<>();
        LambdaQueryWrapper<PlantEnvironment> wrapper = queryWrapper.eq(PlantEnvironment::getPlantId, plants.getId());
        PlantEnvironment environmentDtoById = plantEnvironmentMapper.selectOne(wrapper);
        
        flowerDetailsDto.setBlossom(environmentDtoById.getBlossom());
        flowerDetailsDto.setHumidityMax(environmentDtoById.getOptimalHumidityMax());
        flowerDetailsDto.setTemperatureMin(environmentDtoById.getOptimalTemperatureMin());
        flowerDetailsDto.setTemperatureMax(environmentDtoById.getOptimalTemperatureMax());
        flowerDetailsDto.setHumidityMin(environmentDtoById.getOptimalHumidityMin());
        flowerDetailsDto.setLightIntensity(environmentDtoById.getOptimalLightIntensity());
        flowerDetailsDto.setFertilization(environmentDtoById.getFertilizationFrequency());
        flowerDetailsDto.setOptimalSoilMoisture(environmentDtoById.getOptimalSoilMoisture());

        return flowerDetailsDto;
    }

    /**
     * 获取环境温度
     *
     * @return FlowerEnvirmentDataDto
     */
    @Override
    public FlowerEnvirmentDataDto queryFlowerEnvirmentData() {
        // 查询最新的环境数据
        EnvironmentData environmentData = environmentDataMapper.selectOne(
                new LambdaQueryWrapper<EnvironmentData>().orderByDesc(EnvironmentData::getId).last("limit 1")
        );

        // 查询最新的光照数据
        LightData lightData = lightDataMapper.selectOne(
                new LambdaQueryWrapper<LightData>().orderByDesc(LightData::getId).last("limit 1")
        );

        // 查询最新的土壤数据
        SoilData soilData = soilDataMapper.selectOne(
                new LambdaQueryWrapper<SoilData>().orderByDesc(SoilData::getId).last("limit 1")
        );

        // 创建 DTO
        FlowerEnvirmentDataDto flowerEnvirmentDataDto = new FlowerEnvirmentDataDto();

        // 使用 Optional 处理可能的 null 值
        flowerEnvirmentDataDto.setHumidity(Optional.ofNullable(environmentData)
                .map(EnvironmentData::getHumidity)
                .map(BigDecimal::valueOf)
                .orElse(BigDecimal.ZERO));

        flowerEnvirmentDataDto.setTemperature(Optional.ofNullable(environmentData)
                .map(EnvironmentData::getTemperature)
                .orElse(BigDecimal.valueOf(0.0)));

        flowerEnvirmentDataDto.setSoilMoisture(Optional.ofNullable(soilData)
                .map(SoilData::getSoilMoisture)
                .orElse(BigDecimal.valueOf(0.0)));

        flowerEnvirmentDataDto.setLightIntensity(Optional.ofNullable(lightData)
                .map(LightData::getLightIntensity)
                .orElse(BigDecimal.valueOf(0.0)));

        return flowerEnvirmentDataDto;
    }


}




